package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/database"
	"server/internal/pkg/response"
)

// EnterpriseTypeApi 单位性质
var EnterpriseTypeApi = new(enterpriseTypeApi)

type enterpriseTypeApi struct {
	model.EnterpriseType
}

// List 列表
func (a enterpriseTypeApi) List(c *gin.Context) {
	Db := database.DB         //初始化Db
	Db = Common.Query(Db, c)  //查询构造
	Db = Common.Paging(Db, c) //分页

	//快速搜索
	quickSearch := c.Query("quickSearch")
	if quickSearch != "" {
		Db = Db.Where("name like ?", "%"+quickSearch+"%")
	}

	_, list, total := serv.EnterpriseType.Reads(Db)

	response.SuccessList(c, list, total)
}

// Detail 单条
func (a enterpriseTypeApi) Detail(c *gin.Context) {
	id := c.Query("id")

	_, detail := serv.EnterpriseType.Read(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a enterpriseTypeApi) Add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}
	if err := serv.EnterpriseType.Create(a.EnterpriseType); err.Error == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Fail(c, err.Error, "添加失败")
	}
}

// Edit 编辑
func (a enterpriseTypeApi) Edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}

	if err := serv.EnterpriseType.Update(a.EnterpriseType); err.Error == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Fail(c, err.Error, "编辑失败")
	}
}

// Del 删除
func (a enterpriseTypeApi) Del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}

	if err := serv.EnterpriseType.Delete(param.Ids); err.Error == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Fail(c, err.Error, "删除失败")
	}
}
